#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<openssl/hmac.h>
#include<openssl/md5.h>
 
int output(char *p, unsigned char* pwd, int len) {
	int i;
	printf("%s", p);
	for (i = 0; i < len; i++) {
		printf("%x", pwd[i]);
	}
	printf("\n");
	return 0;
}
 
int main(int argc, char *argv[]) {
	if (argc < 2) {
		fprintf(stderr, "%s <original password><salt password><hash length>\n",
				argv[0]);
		return 1;
	}
	int i, hashLen;
	unsigned char *originalPwd;
	unsigned char *saltPwd;
	originalPwd = (unsigned char *) malloc(strlen(argv[1]) + 1); //argv[1]是初始密码
	saltPwd = (unsigned char *) malloc(strlen(argv[2]) + 1); //argv[2]是加盐：是指通过在密码任意固定位置插入特定的字符串，让散列后的结果和使用原始密码的散列结果不相符
	strcpy(originalPwd, argv[1]);
	strcpy(saltPwd, argv[2]);
	hashLen = atoi(argv[3]);	//设置加密密码的长度
	unsigned char encryptPwd[hashLen];
 
	printf("Before add salt into the original password:\n");
	MD5((unsigned char *) originalPwd, strlen(originalPwd), encryptPwd);//使用MD5算法对密码进行加密（不加盐），并输出加密前后密码
	output("Original Password = ", (unsigned char *) originalPwd,
			strlen(originalPwd));
	output("Encrypt Password = ", (unsigned char *) encryptPwd, hashLen);
 
	printf("\nAfter add salt into the original password:\n");
	memset(encryptPwd, 0, sizeof(encryptPwd));
	strcat(originalPwd, saltPwd);
	MD5((unsigned char *) originalPwd, strlen(originalPwd), encryptPwd);//使用MD5算法对密码进行加密（加盐），并输出加密前后密码
	output("Original Password = ", (unsigned char *) originalPwd,
			strlen(originalPwd));
	output("Encrypt Password = ", (unsigned char *) encryptPwd, hashLen);
 
	return 0;
}
